package com.tanklab.signature.controller;

import com.tanklab.signature.common.util.JwtUtils;
import com.tanklab.signature.ds.req.ApproveRequestReq;
import com.tanklab.signature.ds.resp.CommonResp;
import com.tanklab.signature.service.ApprovalService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/signature/approvallogs")
@Api(tags = "审批管理")
@ApiModel
public class ApprovallogsController {
    @Autowired
    private ApprovalService approvalService;

    @Autowired
    private JwtUtils jwtUtils;

    @ApiOperation(value="审批申请")
    @PostMapping("/approve")
    public CommonResp approveRequest(@RequestBody ApproveRequestReq approveRequestReq, HttpServletRequest request) {

        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        // 从Token提取openid
        String openid = jwtUtils.getOpenidFromToken(token);

        return approvalService.approveRequest(
                approveRequestReq.getRequestId(),
                approveRequestReq.getAction(),
                approveRequestReq.getComments(),
                openid
        );
    }

    @ApiOperation(value = "查询待我审批的申请")
    @GetMapping("/pending")
    public CommonResp getPendingApprovals(HttpServletRequest request) {

        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        // 从Token提取openid
        String openid = jwtUtils.getOpenidFromToken(token);

        return approvalService.getPendingApprovals(openid);
    }

    @ApiOperation(value = "查询我的审批历史")
    @GetMapping("/history")
    public CommonResp getApprovalHistory(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        // 从Token提取openid
        String openid = jwtUtils.getOpenidFromToken(token);

        return approvalService.getApprovalHistory(openid);
    }

    @ApiOperation(value = "查询申请的审批日志")
    @GetMapping("/logs/{requestId}")
    public CommonResp getRequestApprovalLogs(
            @ApiParam(name = "requestId", value = "申请ID", required = true)
            @PathVariable("requestId") Long requestId) {
        return approvalService.getRequestApprovalLogs(requestId);
    }
}